#!/bin/bash
set -e

source $(dirname $0)/version

OS_ARCH_ARG_LINUX="amd64 arm arm64"
OS_ARCH_ARG_WINDOWS="amd64"
OS_ARCH_ARG_DARWIN="amd64"

LD_INJECT_VALUES="-X github.com/rancher/steve/pkg/version.Version=$VERSION
                  -X github.com/rancher/steve/pkg/version.GitCommit=$COMMIT"

[ "$(uname)" != "Darwin" ] && LINKFLAGS="-extldflags -static -s"

pushd $GIT_SOURCE

if [ -n "$CROSS" ]; then
    for ARCH in ${OS_ARCH_ARG_LINUX}; do
        OUTPUT_BIN="bin/kube-explorer-linux-$ARCH"
        echo "Building binary for linux/$ARCH..."
        GOARCH=$ARCH GOOS=linux CGO_ENABLED=0 go build -tags embed \
                -ldflags \
                "$LD_INJECT_VALUES $LINKFLAGS" \
                -o ${OUTPUT_BIN}
    done

    for ARCH in ${OS_ARCH_ARG_WINDOWS}; do
        OUTPUT_BIN="bin/kube-explorer-windows-$ARCH.exe"
        echo "Building binary for windows/$ARCH..."
        GOARCH=$ARCH GOOS=windows CGO_ENABLED=0 go build -tags embed \
                -ldflags \
                "$LD_INJECT_VALUES $LINKFLAGS" \
                -o ${OUTPUT_BIN}
    done

    for ARCH in ${OS_ARCH_ARG_DARWIN}; do
        OUTPUT_BIN="bin/kube-explorer-darwin-$ARCH"
        echo "Building binary for darwin/$ARCH..."
        GOARCH=$ARCH GOOS=darwin CGO_ENABLED=0 go build -tags embed \
                -ldflags \
                "$LD_INJECT_VALUES" \
                -o ${OUTPUT_BIN}
    done
else
    # only build one for current platform
    CGO_ENABLED=0 go build -tags embed \
        -ldflags \
        "$LD_INJECT_VALUES $LINKFLAGS" \
        -o bin/kube-explorer
fi

for f in $(ls ./bin/); do
    upx -o $DAPPER_SOURCE/bin/$f bin/$f
done

popd
